<?php

/**
 * Description of Flickr
 *
 * @author Pavel Homolka
 */

use Nette\Diagnostics\Debugger;

class Flickr {
    const api_key = 'd64e05f88d5f2e48b12cd8edff541dc4';
    const format = 'php_serial';

    private $session;

    public function __construct(PhotosSession $photoSession) {
        $this->session = $photoSession;
    }

    public function search($text, $perPage, $lat = NULL, $lon = NULL, $radius = NULL) {

        $this->session->clear();

        $params['api_key'] = self::api_key;
        $params['format'] = self::format;
        $params['method'] = 'flickr.photos.search';
        $params['per_page'] = $perPage;
        $params['text'] = $text;
        if (($lat || $lon) != NULL) {
            $params['lat'] = $lat;
            $params['lon'] = $lon;
            $params['radius'] = $radius;
        }
        $params['extras'] = 'date_upload, date_taken, owner_name, geo, tags, url_t, url_l';

        Debugger::timer();
        $result = self::send($params);
        $this->session->setCommunication(Debugger::timer());
        $this->session->add($result['photos']['photo']);

        return $result['photos']['photo'];
    }

    /**
     * Odeslani pozadavku Flickru
     * @param array $params
     * @return array  
     */
    private function send($params) {
        $encoded_params = array();

        foreach ($params as $k => $v) {

            $encoded_params[] = urlencode($k) . '=' . urlencode($v);
        }

        // call the API and decode the response
        $url = "http://api.flickr.com/services/rest/?" . implode('&', $encoded_params);

        $rsp = file_get_contents($url);

        $rsp_obj = unserialize($rsp);

        if ($rsp_obj['stat'] == 'ok') {
            return $rsp_obj;
        } else {
            throw new Exception($rsp_obj['message']);
        }
    }

}

?>
